<template>
  <div class="nav-bar-main">
    <div class="nav-bar w">
      <div class="nav-bar-left">
        <router-link to="/"><img src="@/assets/logo.png" alt="" width="180px" height="50px"></router-link>
      </div>
      <div class="nav-bar-right">
        <ul>
          <li><a href="javascript:void(0);">提出意见</a></li>
          <li><a href="javascript:void(0);">加入我们</a></li>
          <li v-if="getLoginStatue">
            <router-link to="/user/order">我的预定</router-link>
          </li>
          <li><router-link to="/register">注册</router-link></li>
          <li v-if="!getLoginStatue">
            <i class="el-icon-user-solid"></i><a href="javascript:void(0);" style="padding-left: 0" @click="doLogin">登录</a>
          </li>
          <li v-else style="padding: 0 15px 0 5px">
            <el-dropdown style="cursor: pointer">
            <span class="el-dropdown-link" >
              {{getUserInfo?getUserInfo.name:''}}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <span @click="doUserCenter">个人中心</span>
                </el-dropdown-item>
                <el-dropdown-item>
                  <span @click="logout">退出登录</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </li>
          <li v-if="getLoginStatue">
            <el-avatar class="user-avatar" size="small" :src="getUserInfo?getUserInfo.avatar:''"></el-avatar>
          </li>
        </ul>
      </div>
    </div>
    <!--登录-->
    <el-dialog
        title="欢迎登录"
        :visible="showLogin || this.$store.getters.getShowLogin"
        :close-on-click-modal="false"
        width="30%"
        :before-close="closeLogin"
        @open="openLogin"
        center>
      <el-form ref="loginForm" status-icon :rules="loginFormRule" :model="userInfo" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userInfo.password" type="password" show-password clearable></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="17">
            <el-form-item label="验证码" prop="code">
              <el-input v-model="userInfo.code"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-image
                style="width: 100px; height: 40px"
                :src="captcha"
                fit="fit" @click="getCaptchas"></el-image>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="closeLogin">取 消</el-button>
      <el-button type="primary" @click="okLogin">登录</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
import {checkCaptcha, getCaptcha, login} from "@/network/common";
import {SET_SHOW_LOGIN} from "@/store/mutations-type";

export default {
  name: "NavBar",
  data(){
    return{
      userId:0,
      showLogin:false,
      userInfo:{
        username:'',
        password:'',
        code:'',
      },
      captcha:'',//验证码
      key:'',
      loginFormRule:{
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 15, message: '长度限制：3-15个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { min: 5, max: 15, message: '长度限制：5-15个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'change' },
          { min: 5, max: 5, message: '长度限制：5个字符', trigger: 'blur' }
        ],
      },
    }
  },
  methods:{
    //登录
    doLogin(){
      this.showLogin = true
    },
    openLogin(){
      this.getCaptchas()//获取验证码
    },
    //用户中心
    doUserCenter(){
      this.$router.push('/user/center')
    },
    logout(){
      this.$store.dispatch('logout').then(()=>{
        this.$router.push("/")
      })
    },
    //取消登录
    closeLogin() {
      this.$refs.loginForm.clearValidate()//清除表单验证
      this.$store.commit(SET_SHOW_LOGIN,false)
      this.showLogin = false//关闭登录界面

    },
    //登录
    okLogin:async function(){
      await this.$refs.loginForm.validate(async (valid) => {
        if (await valid) {//数据格式验证完成
          await checkCaptcha(this.userInfo.code,this.key).then(async ()=>{//验证码验证完成
            await login(this.userInfo).then(async res=>{//登录请求
              this.userId = res.data.data.id
              //调用store的action执行登录的逻辑 清除标志、存储token数据和用户数据、跳转到指定权限页面
              await this.$store.dispatch('doLogin', {'token': res.headers['authorization'], "userInfo": res.data.data})
              .then(async ()=>{
                this.closeLogin()//关闭登录界面显示并且清除表单验证
                if (res.data.code===300){//管理员登录
                  await this.$router.push('/admin/dashboard')//跳转到管理界面
                }
              })
            })
          }).catch(()=>{//验证码验证失败
            this.getCaptchas()//刷新验证码
          })
        }
      });
    },
    //获取验证码
    getCaptchas(){
      getCaptcha().then(res=>{
        this.captcha = res.data.data.captcha
        this.key = res.data.data.key
      })
    },
  },
  computed:{
    getUserInfo(){
      return this.$store.getters.getUserInfo
    },
    getLoginStatue(){
      return this.$store.getters.getLoinStatue
    }
  },
}
</script>

<style scoped>
  .nav-bar-main {
    background-color: #f6f4f4;
  }
  .w {
    width: 1200px;
    margin: 0 auto;
  }
  li {
    list-style: none;/*去除原点*/
  }
  a {
    text-decoration: none;
  }
  .nav-bar {
    height: 60px;
    margin: 0 auto;
  }
  .nav-bar-left {
    float: left;
  }
  .nav-bar-right {
    float: right;
    height: 100%;
  }
  .nav-bar-right ul li {
    float: right;
  }
  .nav-bar-right ul li a {
    display: inline-block;/*块级元素*/
    padding: 0 15px;
    font-size: 14px;
    font-weight: 400;
    color: #050505;
  }

</style>